<template>
  <div class="app-container">
<!--    {{id}}-->
    <el-form :model="user" label-width="80px" :rules="CenterRules" status-icon ref="user">
      <el-form-item label="用户姓名" prop="username">
        <el-input v-model="user.username"  style="width: 217px;"></el-input>
      </el-form-item>

      <el-form-item label="性别">
        <el-select v-model="state" placeholder="用户性别">
          <el-option
            v-for="item in options"
            :key="item.state"
            :label="item.label"
            :value="item.state">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="角色">
<!--        <el-checkbox-group v-model="role">-->
<!--          <el-checkbox v-for="item in roles" :label="item.id">-->
<!--            {{item.name}}-->
<!--          </el-checkbox>-->
<!--        </el-checkbox-group>-->
        <el-radio-group v-model="role">
          <el-radio  v-for="item in roles" :label="item.id">
            {{item.name}}
          </el-radio>
        </el-radio-group>

      </el-form-item>


      <el-form-item label="头像">
        <!--     图片上传-->
        <el-upload
          action
          list-type="picture-card"
          :auto-upload="false"
          :file-list="fileList"
          :limit="1"
          :on-change="changeImg"
          :on-remove="removeImg">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>




      <el-form-item>
<!--        给修改前加上一个判断条件 是否需要修改-->
        <el-button type="primary" @click="onSubmit('user')">修改</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<style>
  /*#app{*/
  /*  text-align: left;*/
  /*}*/
  .el-form{
    float: left;
  }
</style>

<script>
import axios from "axios";

export default {
  name: "roleEditView",
  data(){       //data:{}
    var checkUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('姓名不能为空'));
      }
      setTimeout(() => {
        if (value.length>5) {
          callback(new Error('姓名不能超过5个字符'));
        }else{
          callback();
        }
        // else {
        //   if (value < 18) {
        //     callback(new Error('必须年满18岁'));
        //   } else {
        //     callback();
        //   }
        // }
      }, 1000);
    };
    return {
      user:{
        id:'',
        username:'',
      },
      options: [{
        // value: '选项1',
        label: '男',
        state: '1',
      }, {
        // value: '选项2',
        label: '女',
        state: '2',
      } ],
      state: '',
      role:0,  //用户当前的角色
      roles:[], //所有的角色
      text:'',
      CenterRules:{
        username: [
          { validator:checkUsername,message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        // state: [
        //   { required: true, message: '请选择用户性别', trigger: 'change' }
        // ],
        // role: [
        //   { required: true, message: '请选择用户角色', trigger: 'change' }
        // ],
      },
      fileList: [
        {
          name: 'files',
          url: '',
        },
      ]

    }
  },
  //获取数据
  created(){
    //通过this.$route.query.id获取当前路由参数中的id值
    // alert(this.$route.query.id)
    this.user.id=parseInt(this.$route.query.id)
    axios({
      url: '/api/user/queryById/'+this.user.id,
      method: 'post',
      // data: this.user,
      headers:{"Authorization":"Bearer "+this.$store.state.user.token}
    }).then(res => {
      // console.log(res.data.data)
      this.user.username=res.data.data[0].username
      //用户性别
      // console.log(res.data.data[0].state)
      //自己的所有角色   (查询到自己的角色id)
      var arr=res.data.data[0].roleList
      // console.log(arr)
      for (const key in arr) {
        // this.role.push(arr[key].id)
        this.role=arr[key].id
      }
      if(res.data.data[0].state==1){
        this.state='男'
      }else{
        this.state='女'
      }
      this.fileList[0].name="files"

      this.fileList[0].url="/api"+res.data.data[0].path
      //   this.options.pranceholdText='男'
      // }else{
      //   this.options.pranceholdText='女'
      // }

    })

    //查询所有的角色
    axios({
      url: '/api/role/queryRoleAll',
      method: 'post',
      headers:{"Authorization":"Bearer "+this.$store.state.user.token}
    }).then(res => {
      // console.log(res.data.data)
      // this.roles=res.data.data
      res.data.data.forEach(item=>{
        this.roles.push(item)
      })



    })


  },

  methods:{
    sta2(row){
      // console.log(row)
      var arr=[]
      var roles=row.roleList
      console.log(roles)
      for (const key in roles) {
        arr.push(roles[key].name)
      }

      return arr.join(",")
    },
    //修改数据
    //修改数据
    onSubmit(formName){
      // console.log(this.role)
      // for (const key in this.roles) {
      //   console.log("roles"+this.roles[key].id)
      // }

      this.$refs[formName].validate(validate=>{
        if(validate){
          // 创建表单对象
          var formData = new FormData();
          // 创建表格对象
          var formData = new window.FormData()
          if(this.state== '男'){
            this.state='1'
            formData.append("state", this.state)
          }else if(this.state== '女'){
            this.state='2'
            formData.append("state", this.state)
          }
          formData.append("state", this.state)
          for (const key in this.user){
            formData.append(key,this.user[key])
          }
          // 将fileList中的文件添加到formData中 循环添加文件对象中的raw 后台接收的二进制
          for (const key in this.fileList) {
            formData.append("files",this.fileList[key].raw)
          }
          // for (const key in this.role) {
          //   alert("role"+this.role[key])
          //   formData.append("rids",this.role[key])
          // }
          formData.append("rids",this.role)
          this.$confirm('是否确定修改?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            axios({
              url:"/api/user/edit",
              method:"post",
              data:formData,
              //添加请求头
              // headers:{"Content-Type":"multipart/form-data"}
              headers:
                {"Authorization":"Bearer "+this.$store.state.user.token
                  ,"Content-Type":"multipart/form-data"
                }
            }).then(res=>{
              if(res.data.code==1){
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
                //返回医生信息表
                this.$router.push("/user")
              }else {
                this.$message({
                  message: res.data.message,
                  type: 'error'
                });
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消修改'
            });
          });

        }else{
          this.$message({
            message: '请根据提示修改信息',
            type:'error'
          })
        }
      })

    },
    cancel(){
      this.$router.push("/user")
    },


    //删除文件
    removeImg(file){
      //根据uid删除对应的文件
      for (const key in this.fileList) {
        if (this.fileList[key].uid === file.uid) {
          this.fileList.splice(key, 1)
        }
      }
    },


    //添加图片
    changeImg(file){
      //直接将文件添加到数组中
      this.fileList.push(file)
      console.log("添加"+file.name)
    },



  }

}
</script>

<style scoped>

</style>
